package org.sample.commons.edoc;

import org.sample.commons.bean.BeanUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by alan on 17/6/9.
 */
public class Columns {

    protected Class clazz;

    protected boolean border;

    protected String fontName = "微软雅黑";

    protected List<Column> columns = new ArrayList<>();

    public Columns(Class clazz) {
        this.clazz = clazz;
    }

    public Columns(Class clazz, String fontName) {
        this.clazz = clazz;
        this.fontName = fontName;
    }

    public Columns(Class clazz, boolean border) {
        this.clazz = clazz;
        this.border = border;
    }

    public Columns(Class clazz, String fontName, boolean border) {
        this.clazz = clazz;
        this.fontName = fontName;
        this.border = border;
    }

    public Columns addColumn(String propertyName) {
        return addColumn(propertyName, null);
    }

    public Columns addColumn(String propertyName, String title) {
        return addColumn(propertyName, title, null);
    }

    public Columns addColumn(String propertyName, String title, Format format) {
        return addColumn(propertyName, title, null, format);
    }

    public Columns addColumn(String propertyName, String title, Boolean numeric, Format format) {
        String[] names = propertyName.split("\\.");
        if (title == null)
            title = names[0];
        Method[] readMethods = getReadMethods(names);
        columns.add(new Column(readMethods, title, numeric, format));
        return this;
    }

    public Method[] getReadMethods(String[] names) {
        Method[] readMethods = new Method[names.length];

        Class<?> rootClazz = this.clazz;
        for (int i = 0; i < names.length; i++) {
            String name = names[i];
            Method readMethod = BeanUtils.getReadMethod(rootClazz, name);
            readMethods[i] = readMethod;

            Class<?> clazz = readMethod.getReturnType();
            if (clazz.isAssignableFrom(List.class)) {
                rootClazz = BeanUtils.getGenericType(rootClazz, name);
            } else if (clazz.isArray()) {
                rootClazz = clazz.getComponentType();
            } else {
                rootClazz = clazz;
            }
        }
        return readMethods;
    }
}